//
//  AddressViewController.m
//  jungoo
//
//  Created by Dang Quang Trung on 9/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AddressViewController.h"
@implementation NSDictionary (Extension)

- (id)newObjectForKey:(id)aKey
{
    id rez = [self objectForKey:aKey];
    
    return ([rez isKindOfClass:[NSNull class]] ? nil : rez);
}
@end

@implementation AddressViewController

@synthesize  myCell;
@synthesize address;
@synthesize data;
@synthesize txtVenue,txtPostcode,txtCity,txtAddress1,txtAddress2;

#pragma mark - Actions

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) geoCodeUsingAddress:(NSString *)addressStr
{
    NSString *esc_addr =  [addressStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    NSLog(@"%@",result);
    NSDictionary *dic = [result JSONValue];
    if (! [[dic newObjectForKey:@"status"] isEqualToString:@"OK"]) {
        //[JGoUtility showAlert:@"Could not found the address."];
        return;
    }else {
        NSArray *dic1 = [dic newObjectForKey:@"results"];
         NSLog(@"%@",dic1);
        NSDictionary *dic2;
        if (dic1 != nil)  {
            dic2 = [dic1 objectAtIndex:0];
            NSLog(@"%@",dic2);

        }
        NSDictionary *dic3 = [dic2 newObjectForKey:@"geometry"];
        if (dic3 != nil){
            NSDictionary *loc = [dic3 newObjectForKey:@"location"];
            NSLog(@"%@",loc);
            [data setObject:[loc newObjectForKey:@"lat"] forKey:@"addressLat"];
            [data setObject:[loc newObjectForKey:@"lng"] forKey:@"addressLon"];
        }
    }
    
}

- (void)delayGetLocation:(MBProgressHUD*)progress
{
    NSString *strAdd = [NSString stringWithFormat:@"%@ %@ %@ %@ %@",txtVenue.text,txtAddress1.text,txtAddress2.text,txtPostcode.text,txtCity.text];
    [self geoCodeUsingAddress:strAdd];
    [progress hide:YES];
    if ([data newObjectForKey:@"addressLat"] == nil || [data newObjectForKey:@"addressLon"] == nil) {
        [JGoUtility showAlert:@"Could not found the address."];
        return;
    }
    NSLog(@"addressLat = %@",[data newObjectForKey:@"addressLat"]);
    NSLog(@"addressLon = %@",[data newObjectForKey:@"addressLon"]);
    //Store all textfield values into Address field of CreateEventData struct.
    NSString *str = [NSString stringWithFormat:@"%@;%@;%@;%@;%@",txtVenue.text,txtAddress1.text,txtAddress2.text,txtPostcode.text,txtCity.text];
    NSLog(@"Address = %@",str);
    [data setObject:@"" forKey:@"address"];
    [data setObject:str forKey:@"address"];
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)done:(id)sender
{
    
    [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                            target:self
                             title:@"Saving..."
                          selector:@selector(delayGetLocation:)];
    
    
}

#pragma mark - Init Control

- (void)applyAppearance
{
    [self setRightButtonImageActiveName:nil 
                           inactiveName:@"done-button" 
                                 target:self 
                                 action:@selector(done:)];
    [self setLeftButtonImageActiveName:nil 
                          inactiveName:@"back-button.png" 
                                target:self 
                                action:@selector(back:)];
    [self setTitle:@"Address"];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg"]];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self applyAppearance];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc
{
    [data release];
    [txtVenue release];
    [txtPostcode release];
    [txtCity release];
    [txtAddress1 release];
    [txtAddress2 release];
    [myCell release];
    [super dealloc];
}
#pragma mark - TableView Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 1:
        {
            return 2;
            break;
        }
        
        default:
            return 1;
            break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}



- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    
    static NSString *AddressCellIdentifier = @"AddressCell";
    cell = [tableView dequeueReusableCellWithIdentifier:AddressCellIdentifier];
    if (cell == nil) {
        cell  = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:AddressCellIdentifier] autorelease];
        [[NSBundle mainBundle] loadNibNamed:@"AddressCell" owner:self options:nil];
        cell = self.myCell;
        self.myCell = nil;  
    } 
    UITextField *txtField = (UITextField*)[cell viewWithTag:1];
    switch (indexPath.section) {
        case 0: 
        {
            //cell.backgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
            self.txtVenue = txtField;
            txtField.placeholder = @"Venue/Room";
            break;
        }
        case 1: 
        {
            if (indexPath.row == 0) {
                txtField.placeholder = @"First line of address";
                 self.txtAddress1 = txtField;
            }else {
                txtField.placeholder = @"Second line of address";
                 self.txtAddress2 = txtField;
            }
            
            break;
        }
        case 2: 
        {
            txtField.placeholder = @"Postcode";
             self.txtPostcode = txtField;
            break;
        }
        case 3: 
        {
            txtField.placeholder = @"City";
             self.txtCity = txtField;
            break;
        }   
        default:
        {
            break;
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}

#pragma mark - TextField Delegete && TextView Delegete

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 218, 0)];
    [self.tableView scrollToRowAtIndexPath:indexPath 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:YES];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:YES];
    return YES;
}

@end
